#!/usr/bin/env python
# coding: utf-8

############################################################################
#                   2013/02/27  Ver 1.1                                    #
#                                                                          #
#Replace standby opca wa.py                                                #
#Author:Fan Chuanlin                                                       #
#                                                                          #
#Release note:                                                             #
#                                                                          #
############################################################################


import os
import re
import shutil
import zipfile
import time
import datetime
import string
from onshs.ne.tnxxx.tnxxxcfg_basecase import *


log_node_prefix = "replace_standby_opca"
log_node_fail = log_node_prefix+r"_fail"
log_node_normal = log_node_prefix+r"_normal"
log_node_success = log_node_prefix+r"_success"
log_node_summary = log_node_prefix +r"_summary"

log_connect_fail = "connect ip:%s failed\n"

class TestCase(TnxxxCfg_BaseCase):
    """
    TestCase
    """
    OPTIONS = [
        {
            'opt' : '--cfgfile',
            'dest': 'cfgfile',
            'metavar' : 'CFGFILE',
            'help' : 'the file of ip list configuration',
            'required' : False,
            'default' : "ip2.txt"
        },
    ]
    
        #初始化信息
    def info_init(self):
        self.info_dic = {}  

        return True
    
    def get_iplist_from_file(self):
        iplist_filted = []                
        if os.path.isfile(os.getcwd()+r'/'+ self.iplistfile):
            iplist = open(os.getcwd()+r'/'+ self.iplistfile)
        else:
            self.info_show(log_node_fail, "the file %s isn't existed.\n" %(self.iplistfile))
            self.info_show(log_node_summary, "the file %s isn't existed.\n" %(self.iplistfile))
            
            return iplist_filted 
        
        for line in iplist:
            if re.match(r'^\s*$', line) is not None : continue # 忽略空白行
            if re.match(r'^\s*#', line) is not None : continue # 忽略注释行            
            iplist_filted.append(line.strip('\n'))        
            
        iplist.close()
        
        return iplist_filted
    
    #跟LOG相关函数
    def info_show(self, node, info):
        if not self.info_dic.has_key(node):
            self.info_dic[node] = ""
        self.info_dic[node] += info + '\n'
        return True

    def info_file_clear(self):
        if os.path.exists(os.getcwd()+r'/log'):
            shutil.rmtree(os.getcwd()+r'/log')
        
        return True    
    
    def info_file_save(self):
        path = os.getcwd()+'/LOG/'
        
        for node in self.info_dic:
            info_list = open(path+node+'_'+self.worktime+'.txt','a')            
            info_list.write(self.info_dic[node])
            info_list.close()
        return True

    def get_the_customer_input(self, note):
        rtnstr  = raw_input(note)
        while True:
            if rtnstr.upper() == "Y" or   rtnstr.upper() == "N":
                break
            else:
                rtnstr  = raw_input("Input < y or n > :\n")
                
        return    rtnstr.upper()
        
    def getMasterPPCbySW(self):
        slotList = []
        cmd = r'''$.dbgcli.0.Cmd "queryasyn valid 1, NeStat, (MasterPPC), *"'''
        rtn_str = self.tnxxx.send_rtn_str(cmd, self.get_ne_ip(0), 0, MTN_PORT)
        if rtn_str == '':
            print "\n\n Task stop fail on ip:%s\n\n" % self.get_ne_ip(0)
            
            self.info_show(log_node_fail, log_connect_fail%(self.get_ne_ip(0)))
            self.info_show(log_node_summary, "replace_standby_opca ne:%s failed.\n"%(self.get_ne_ip(0)))
            
            return 0
        
        slotList = re.findall(r"{\r\n  (\d)\r\n}", rtn_str, 0)
        
        if slotList == []:
            return 0
        else:
            return (int)(slotList[0])
    
    def getMasterPPCbyHW(self):
        slotList = []
        cmd = r'$.necli.0.CmdEx "GetSccStatus",{}'
        rtn_str = self.tnxxx.send_rtn_str(cmd, self.get_ne_ip(0), 0, MTN_PORT)
        if rtn_str == '':
            print "\n\n Task stop fail on ip:%s\n\n" % self.get_ne_ip(0)
            
            self.info_show(log_node_fail, log_connect_fail%(self.get_ne_ip(0)))
            self.info_show(log_node_summary, "replace_standby_opca ne:%s failed.\n"%(self.get_ne_ip(0)))
            
            return 0 
        slotList = re.findall(r"localPos:(\d)", rtn_str, 0)
        
        if slotList == []:
            return 0
        else:
            return (int)(slotList[0])
        
    def my_sleep(self, seconds, interval):
        
        tempseconds = seconds
        for i in range(seconds/interval):
            SECONDS = tempseconds%60
            MINUTES = (tempseconds/60)%60
            HOURS = (tempseconds/3600)%24
            DAYS = (tempseconds/(3600*24))
            print "Countdown = %2d DAYS  %2d H:%2d M:%2d S" % (DAYS, HOURS, MINUTES, SECONDS)            
            time.sleep(interval)
            tempseconds = tempseconds - interval
            
    def suspend_task_check(self, slot):
        
        task_list = ["scht[7]", "scht[4]", "DSDS[5]"]
        task_list_check = []
        
        cmd = r'g_RebootWhenSuspend = 0'
        rtn_str = self.tnxxx.send_rtn_str(cmd, self.get_ne_ip(0), slot, DEV_PORT)
        
        if rtn_str == '':
            print "\n\n Task stop fail on ip:%s\n\n" % self.get_ne_ip(0)
            
            self.info_show(log_node_fail, log_connect_fail%(self.get_ne_ip(0)))
            self.info_show(log_node_summary, "replace_standby_opca ne:%s failed.\n"%(self.get_ne_ip(0)))
            
            return False
        else:
            #直接suspend task
            for task in task_list:
                rtn_str = self.tnxxx.send_rtn_str(r'ts "%s"' % task, self.get_ne_ip(0), slot, DEV_PORT)
            
            #可能需要延时一下
            time.sleep(5)
            
            #检查任务状态
            rtn_str = self.tnxxx.send_rtn_str(r'i', self.get_ne_ip(0), slot, DEV_PORT)
            
            task_list_check = re.findall(r"(\S+)\s+\S+\s+\S+\s+\d+\s+SUSPEND\s+", rtn_str, 0)
            
            #判断是否任务都挂起了
            for task in task_list:
                if task not in task_list_check:
                    self.info_show(log_node_fail, "fail: Tasks still running ne:%s.\n" %(self.get_ne_ip(0)))
                    return False
            
        return True
    
    def _execute(self):
        self.iplistfile = self.options.cfgfile
        
        self.info_init()
        
        worktime = str(datetime.datetime.now())
        self.worktime = worktime[:4]+worktime[5:7]+worktime[8:10]+'_'+worktime[11:13]+worktime[14:16]+worktime[17:19]
        self.info_show(log_node_summary, "The operation begin time %s \n"%(self.worktime))
        self.info_file_save()
        self.info_init()
        
        ip_list = self.get_iplist_from_file()
        
        if ip_list != []:
            for ip in ip_list:
                self.set_ne_ip(0, ip)
                 
                #比较两种方式的主用PPC槽位号是否相同
                MasterSlotSW = self.getMasterPPCbySW()
                MasterSlotHW = self.getMasterPPCbyHW()
                
                if MasterSlotHW in [3,4] and MasterSlotSW in [3,4]:
                    if MasterSlotSW != MasterSlotHW:  
                        print "\n\n Task stop fail on ip:%s\n\n" % self.get_ne_ip(0)
                        
                        self.info_show(log_node_fail, "fail: Standby OPCA is not match SW/HW ne:%s.\n" % (self.get_ne_ip(0)))
                        self.info_show(log_node_summary, "replace_standby_opca ne:%s failed.\n"%(self.get_ne_ip(0)))
                        continue
                else:
                    continue
                
                note = "Please confirm whether Slot %d is Standby OPCA (y/n)" % int(7 - MasterSlotSW)
                input = self.get_the_customer_input(note)
                if input == "Y":
                    #suspend standby opca
                    if self.suspend_task_check(int(7 - MasterSlotSW)):
                        print "\n\nTask stop ends to success on ip:%s \n\n" % self.get_ne_ip(0)
                        self.info_show(log_node_success, "replace_standby_opca ne:%s success.\n" % (self.get_ne_ip(0)))
                        self.info_show(log_node_summary, "Task stop ends to success on ip:%s.\n" % (self.get_ne_ip(0)))
            
                else:
                    print "\n\n Task stop fail on ip:%s\n\n" % self.get_ne_ip(0)
                    self.info_show(log_node_fail, "fail: script cancelled ne:%s.\n" %(self.get_ne_ip(0)))
                    self.info_show(log_node_summary, "fail: script cancelled ne:%s.\n" %(self.get_ne_ip(0)))
            
                #每处理一个IP就保存下处理结果
                self.info_file_save()
                self.info_init()
                
        worktime = str(datetime.datetime.now())
        self.worktime_end = worktime[:4]+worktime[5:7]+worktime[8:10]+'_'+worktime[11:13]+worktime[14:16]+worktime[17:19]
        
        self.info_show(log_node_summary, "The operation end time %s "%(self.worktime_end))

        self.info_file_save()
        
        return True
    
if __name__ == "__main__" :
    case = TestCase()
    case.execute()
